package com.hhxy.web;

import com.hhxy.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    UserService service = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("注册doPost方法被调用了");
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("注册doGet方法被调用了");
        //1、获取Service对象
        //2、获取用户输入的请求参数
        //设置编码
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //获取用户输入的验证码，并与生成的进行比对
        String authCode = request.getParameter("checkCode");
        //获取系统生成的验证码
        HttpSession session = request.getSession();
        String authCodeGen = (String) session.getAttribute("authCode");
        System.out.println("authCodeGen"+authCodeGen);//测试输出验证码
        //注意比对忽略大小写
        if(!authCodeGen.equalsIgnoreCase(authCode)){
            //不允许注册
            request.setAttribute("register_msg","注册失败，验证码错误");
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
            return;
        }


        //3、调用Service的方法，将注册的账户信息添加到数据库
        boolean flag = service.register(username, password);//true表示用户名没有重复，可以进行注册
        if(flag){
            //注册成功，跳转到登录界面，并给出提示信息
            request.setAttribute("register_msg","注册成功，请登录");
            //将提示信息请求转发给login.jsp
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }else{
            //注册失败，提示：用户名重复
            request.setAttribute("register_msg","注册失败，用户名已存在");
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        }
    }
}
